//
//  SQLiteManager.m
//  Test
//
//  Created by mac on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "FMDB.h"
#import "SQLiteManager.h"

@interface SQLiteManager ()

@property (nonatomic, strong) FMDatabaseQueue* queue;

@end

static NSString* dbName = @"my.db";

@implementation SQLiteManager

- (FMDatabaseQueue*)queue
{
    if (_queue == nil) {

        NSString* dbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

        dbPath = [dbPath stringByAppendingPathComponent:dbName];

        _queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
    }
    return _queue;
}

+ (instancetype)sharedManager
{
    static SQLiteManager* instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    [instance createTable];
    return instance;
}

//创表
- (void)createTable
{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"db.sql" ofType:nil];
    NSString* sql = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
    [self.queue inDatabase:^(FMDatabase* db) {
        if ([db executeStatements:sql]) {
            NSLog(@"创表成功");
        }
        else {
            NSLog(@"创表失败");
        }
    }];
}

//执行sql返回查询结果
- (NSArray*)execRecordSet:(NSString*)sql
{
    NSMutableArray* arrayM = [NSMutableArray array];
    [self.queue inDatabase:^(FMDatabase* db) {
        FMResultSet* resultSet = [db executeQuery:sql];

        while ([resultSet next]) {
            //装入每一行的结果
            NSDictionary* dict = [NSDictionary dictionary];

            // 1. 有几列
            int colCount = resultSet.columnCount;

            for (int i = 0; i < colCount; i++) {
                // 2. 遍历每一列的列名
                NSString* colName = [resultSet columnNameForIndex:i];
                // 3. 每一列的值
                NSString* colValue = [resultSet objectForColumnName:colName];
                [dict setValue:colValue forKey:colName];
            }
            [arrayM addObject:dict];
        }

    }];

    return arrayM.copy;
}

//执行插入语句
- (void)execInsert:(NSDictionary*)dict
{
    NSString* sql = @"INSERT INTO T_Message (name) VALUES (:name);";

    [self.queue inDatabase:^(FMDatabase* db) {
        if ([db executeUpdate:sql withParameterDictionary:dict]) {
            NSLog(@"执行成功,%zd", [db lastInsertRowId]);
        }
        else {
            NSLog(@"执行失败");
        }
    }];
}

@end
